<template>
  <div
    class="app-container"
    style="
      width: 97%;
      padding: 30px;
      background-color: #fff;

      margin: auto;
      border-radius: 10px;
    "
  >
    <div v-if="kong">
      <el-row :gutter="20">
        <!--用户数据-->
        <el-col :span="24" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
          >
            <el-form-item label="" prop="userName">
              <template #label>
                <span style="font-size: 14px; font-weight: 700; color: #000">
                  激活码 <i class="el-icon-question"></i
                ></span>
              </template>
              <el-input
                v-model="queryParams.activateCode"
                placeholder="请输入激活码"
                clearable
                style="width: 240px; height: 30px"
              />
            </el-form-item>
            <el-form-item label="绑定用户账号" prop="phonenumber">
              <template #label>
                <span style="font-size: 14px; font-weight: 700; color: #000">
                  绑定用户账号 <i class="el-icon-question"></i
                ></span>
              </template>
              <el-input
                v-model="queryParams.userName"
                placeholder="请输入绑定用户账号"
                clearable
                style="width: 240px; height: 30px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                placeholder="状态"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item> -->
            <!-- <el-form-item label="创建时间">
                <template #label>
                <span style="font-size: 12px; font-weight: 700; color: #000">
                    创建时间 <i class="el-icon-question"></i
                ></span>
              </template>
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item> -->
            <el-form-item>
              <el-button
                style="color: #fff"
                type="primary"
                color="rgb(78 168 185)"
                @click="handleQuery"
                >搜索</el-button
              >
              <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                style="color: #fff"
                type="primary"
                color="rgb(78 168 185)"
                @click="handleAdd"
                v-hasPermi="['system:user:add']"
                >新增</el-button
              >
            </el-col>
            <!-- <el-col :span="1.5">
              <el-button
                type="success"
                plain
                icon="el-icon-edit"
                size="mini"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:user:edit']"
              >修改</el-button>
            </el-col> -->
            <el-col :span="1.5">
              <el-button
                type="danger"
                plain
                :disabled="multiple"
                @click="dele(ids)"
                v-hasPermi="['system:user:remove']"
                >删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <!-- <el-button
                type="info"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                v-hasPermi="['system:user:import']"
              >导入</el-button> -->
            </el-col>
            <el-col :span="1.5">
              <!-- <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['system:user:export']"
              >导出</el-button> -->
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
              :columns="columns"
            ></right-toolbar>
          </el-row>

          <el-table
            :data="datal"
            @selection-change="handleSelectionChange"
            header-row-class-name="tableRowClassName"
          >
            <el-table-column type="selection" width="55" />
            <!-- <el-table-column type="selection" width="55" /> -->
            <el-table-column prop="createBy" label="创建者" width="150">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column prop="activateCode" label="激活码">
            </el-table-column>
            <el-table-column prop="expireTime" label="有效时间">
            </el-table-column>
            <el-table-column prop="expireTime" label="绑定用户账号">
              <template #default="scope">
                {{ scope.row.userName }}
              </template>
            </el-table-column>

            <el-table-column prop="expireTime" label="状态">
              <template #default="scope">
                <span v-if="scope.row.status == 0">未使用 </span>
                <span v-if="scope.row.status == 1">已使用 </span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="updateTime" label="操作">
              <template #default="scope">
                <div
                  style="
                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  <el-popconfirm
                    @confirm="dele(scope.row.activateId)"
                    title="确定删除吗？"
                  >
                    <template #reference>
                      <span
                        class="bsd"
                        style="
                          display: flex;
                          justify-content: center;
                          align-items: center;
                        "
                      >
                        <el-icon><Delete /></el-icon> 删除
                      </span>
                    </template>
                  </el-popconfirm>

                  <span
                    @click="bianji(scope.row)"
                    class="bsd"
                    style="
                      display: flex;
                      justify-content: center;
                      align-items: center;

                      margin-left: 10px;
                    "
                  >
                    <el-icon class="des"><Edit /></el-icon> 编辑
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div style="margin-top: 10px; display: flex; justify-content: center">
            <el-pagination
              :total="total"
              @change="fchange"
              :page-size="queryParams.pageSize"
              background
              layout="prev, pager, next"
            />
          </div>
        </el-col>
      </el-row>
      <el-dialog
        width="500"
        :title="title"
        v-model="open"
        :before-close="handleClose"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="到期时间" prop="expireTime">
                <template #label>
                  <span style="font-size: 12px; font-weight: 700; color: #000">
                    到期时间 <i class="el-icon-question"></i
                  ></span>
                </template>
                <el-date-picker
                  v-model="form.expireTime"
                  value-format="YYYY-MM-DD"
                  type="date"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item
                v-if="title !== '修改激活码'"
                label="生成条数"
                prop="batchCount"
              >
                <template #label>
                  <span style="font-size: 12px; font-weight: 700; color: #000">
                    生成条数 <i class="el-icon-question"></i
                  ></span>
                </template>
                <el-input-number
                  v-model="form.batchCount"
                  :min="1"
                  :max="1000"
                  label="生成条数"
                ></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            style="color: #fff"
            type="primary"
            color="rgb(78 168 185)"
            @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {getUser, piji, deleji, xiug, getInfo} from "../../api/index";
import {h} from "vue";
import {ElNotification} from "element-plus";
export default {
  name: "User",
  dicts: ["sys_normal_disable", "sys_user_sex"],

  data() {
    return {
      kong: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 100,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        expireTime: undefined,
        batchCount: undefined,
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部

        // 上传的地址
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        activateId: undefined,
        userName: undefined,
        status: undefined,
        activateCode: undefined,
      },
      // 列信息
      columns: [
        {key: 0, label: `用户编号`, visible: true},
        {key: 1, label: `用户名称`, visible: true},
        {key: 2, label: `用户昵称`, visible: true},
        {key: 3, label: `部门`, visible: true},
        {key: 4, label: `手机号码`, visible: true},
        {key: 5, label: `状态`, visible: true},
        {key: 6, label: `创建时间`, visible: true},
      ],
      userLists: [],
      das: {
        activateId: undefined,
        activateCode: undefined,
        expireTime: undefined,
        userName: undefined,
      },
      // 表单校验
      rules: {
        expireTime: [
          {required: true, message: "时间不能为空", trigger: "blur"},
        ],
        batchCount: [
          {required: true, message: "条数不能为空", trigger: "blur"},
        ],
        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
          {
            pattern: /^[^<>"'|\\]+$/,
            message: "不能包含非法字符：< > \" ' \\\ |",
            trigger: "blur",
          },
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      datal: [],
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getList();
    this.yanzheng();
  },
  methods: {
    yanzheng() {
      getInfo().then((response) => {
        if (response.code == 200) {
          if (response.user.roles[0].roleName == "超级管理员") {
            this.kong = true;
          } else {
            ElNotification({
              title: "警告！",
              message: h("i", {style: "color: red"}, "您无权查看！"),
            });
          }
        }
      });
    },
    fchange(e, i) {
      this.queryParams.pageNum = e;
      this.queryParams.pageSize = i;
      this.getList();
    },
    /** 查询用户列表 */
    async getList() {
      const da = await getUser(this.queryParams);
      this.datal = da.rows;
      this.total = da.total;
    },

    async dele(item) {
      const a = await deleji(item);
      if (a.code == 200)
        ElNotification({
          title: "提示1",
          message: h("i", {style: "color: teal"}, "删除成功！"),
        });
      this.getList();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal
        .confirm('确认要"' + text + '""' + row.userName + '"用户吗？')
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        expireTime: undefined,
        batchCount: undefined,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];

      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.activateId);
      console.log(this.ids);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true;
      this.title = "添加激活码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.activateId || this.ids;

      let aa = this.userList.filter((element) => element.activateId == userId);
      this.queryParams.activateCode = aa[0].activateCode;

      listJIhuio(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.title = "修改激活码";
          this.userLists = response.rows;
          this.open = true;
          this.form.expireTime = response.rows[0].expireTime;

          this.das = {
            activateId: aa[0].activateId,
            activateCode: aa[0].activateCode,
            expireTime: this.form.expireTime,
            userName: aa[0].userName,
          };

          this.queryParams.activateCode = undefined;
        }
      );
      // listJIhuio(userId).then(response => {
      //   this.form = response.data;
      //   this.postOptions = response.posts;
      //   this.roleOptions = response.roles;
      //   this.$set(this.form, "postIds", response.postIds);
      //   this.$set(this.form, "roleIds", response.roleIds);
      //
      //
      //   this.form.password = "";
      // });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: "用户密码长度必须介于 5 和 20 之间",
        inputValidator: (value) => {
          if (/<|>|"|'|\||\\/.test(value)) {
            return "不能包含非法字符：< > \" ' \\\ |";
          }
        },
      })
        .then(({value}) => {
          resetUserPwd(row.userId, value).then((response) => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        })
        .catch(() => {});
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },

    bianji(code) {
      this.form.expireTime = code.expireTime;

      this.das = {
        activateId: code.activateId,
        activateCode: code.activateCode,
        expireTime: this.form.expireTime,
      };

      this.open = true;
      this.title = "修改激活码";
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.title == "修改激活码") {
            this.das.expireTime = this.form.expireTime;

            xiug(this.das).then(() => {
              ElNotification({
                title: "提示1",
                message: h("i", {style: "color: teal"}, "编辑成功！"),
              });
              this.open = false;
              this.getList();
              this.title = "添加激活码";
            });
            //   updateUser(this.form).then(response => {

            //   });
          } else {
            piji(this.form).then((response) => {
              if (response.code == 200) {
                this.open = false;

                ElNotification({
                  title: "提示1",
                  message: h("i", {style: "color: teal"}, "添加成功！"),
                });
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      console.log(this.ids);
      const userIds = row.activateId || this.ids;
      this.$modal
        .confirm("是否确认删除此激活码？")
        .then(function () {
          return shanma(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          "</div>",
        "导入结果",
        {dangerouslyUseHTMLString: true}
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>

<style lang="scss" scoped>
.bsd {
  cursor: pointer;
  color: rgb(78 168 185);
  &:hover {
    color: rgb(145, 228, 244);
  }
}
.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}
:deep(.el-dialog) {
  border-radius: 10px;
}
.bm-view {
  width: 100%;

  height: 100%;
}
.el-dropdown-menu {
  padding: 0 !important;
}
:deep(.el-dropdown-menu__item) {
  padding: 0;
}
</style>
